package top.yongyan0624.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.yongyan0624.entity.SysUser;
import top.yongyan0624.service.SysUserService;

import java.util.Collection;

/**
 * @author Yongyan
 * @description: TODO
 * @date 2021/8/16
 **/

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //身份认证：根据username查询出User
        SysUser sysUser = userService.getByUsername(username);

        if (sysUser == null){
            throw new UsernameNotFoundException("该用户名不存在");
        }

        //将用户详细信息传入
        return new AccountUser(sysUser.getId(),sysUser.getUsername(),sysUser.getPassword(),getUserAuthority(sysUser.getId()));

    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     * @param userId
     * @return
     */
    public Collection<? extends GrantedAuthority> getUserAuthority(Long userId) {
        //获取角色（ROLE_admin）和菜单操作权限（sys:user:list）
        String authority = userService.getUserAuthorityInfo(userId); //ROLE_admin,ROLE_normal,sys:user:list...

        //利用工具类方法将 含,号的字符串封装成我们需要的权限list
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }

}
